<template>
  <div>
    <el-dialog 
      v-model="uploadDetailDialog"
      v-dialog-drag 
      :title="t('message.components.importDetails')" 
      width="900px"
    >
      <el-alert
        :title="msg"
        type="error"
        show-icon
      />
      <el-table
        ref="detailTableRef"
        :data="realTableData"
        height="50vh"
      >
        <el-table-column 
          v-for="(item, index) in realTableHeader" 
          :key="index" 
          :prop="item.property" 
          :label="item.label" 
          :width="item.width"
        >
          <template #default="scope">
            <TableText 
              :value="scope.row[item.property] ?? ''" 
              :text-color="scope.row.textColor" 
              :type="item.type" 
            />
          </template>
        </el-table-column>
        <el-table-column v-if="suppleColumn" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            {{ t('message.components.export') }}
          </el-button>
          <el-button type="primary" @click="uploadDetailDialog = false">
            {{ t('message.components.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="slUploadDetailNet">
import { ref, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import TableText from '@/components/TableText'
import { useExport } from '@/hooks/useExport'

interface Props {
  res: {
    resultCode: string
    resultMsg: string
    data: any[]
  }
  tableHeader: {
    label: string
    property: string
    width: string | number
    type?: string
  }[]
  excelName: string
}

const props = defineProps<Props>()
const { t } = useI18n()
const { exportData: $export } = useExport()

const detailTableRef = ref()
const realTableData = ref<any[]>([])
const realTableHeader = ref<any[]>([])
const uploadDetailDialog = ref(false)
const msg = ref('')
const count = ref(0)
const suppleColumn = ref(false)

const tableDoLayout = () => {
  setTimeout(() => {
    nextTick(() => {
      detailTableRef.value?.doLayout()
    })
  }, 0)
}

const changeTableHeader = () => {
  let allWidth = 0
  realTableHeader.value = JSON.parse(JSON.stringify(props.tableHeader))
  realTableHeader.value.unshift({
    label: t('message.components.exportResult'),
    property: 'message',
    width: '300',
    type: 'stateText'
  })
  
  allWidth = realTableHeader.value.reduce((sum, header) => {
    return sum + parseInt(header.width as string)
  }, 0)
  
  suppleColumn.value = allWidth < 864
  tableDoLayout()
}

const changeData = () => {
  realTableData.value = JSON.parse(JSON.stringify(props.res.data))
  const errorData: any[] = []
  const correctData: any[] = []
  
  count.value = 0
  realTableData.value.forEach(item => {
    if (item.canpass) {
      item.message = t('message.components.exportSucceed')
      item.textColor = '#00C695'
      correctData.push(item)
    } else {
      count.value++
      item.textColor = '#FE3E64'
      item.message = `${t('message.components.exportFailed')},${item.errormessage}`
      errorData.push(item)
    }
  })
  
  realTableData.value = [...errorData, ...correctData]
  msg.value = `${t('message.components.inTotal')}${count.value}${t('message.components.rowError')}`
  changeTableHeader()
}

const handleExport = () => {
  if (!realTableData.value.length) {
    ElMessage({
      showClose: true,
      message: '',
      type: 'warning'
    })
    return
  }
  
  ElMessage({
    showClose: true,
    type: 'success',
    message: t('message.components.downloading')
  })
  
  const filterVal = realTableHeader.value.map(header => header.property)
  const tHeader = realTableHeader.value.map(header => header.label)
  const data = realTableData.value.map(v => filterVal.map(j => v[j]))
  
  $export(tHeader, data, props.excelName)
}

watch(() => props.res, () => {
  count.value = 0
  if (props.res.resultCode === '100000') {
    ElMessage({
      showClose: true,
      message: t('message.components.exportSucceed'),
      type: 'success'
    })
    return
  }
  
  if (!props.res.data?.length) {
    ElMessage({
      showClose: true,
      message: props.res.resultMsg,
      type: 'error'
    })
    return
  }
  
  uploadDetailDialog.value = true
  changeData()
  ElMessage({
    showClose: true,
    message: props.res.resultMsg,
    type: 'error'
  })
}, { deep: true })
</script>

<style scoped>
.head-container {
  width: 80%;
  height: 40px;
  background-color: #fff0f0;
  margin: 0 auto 20px auto;
  position: relative;
  border: 1px solid #ff8f9e;
  border-radius: 3px;
}

.text-container {
  position: absolute;
  top: -8px;
  margin-left: 50px;
}

.error-icon {
  position: absolute;
  top: 12px;
  left: 20px;
}
</style>
